#include "ax_fd.h"
#include "ax_time.h"
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

ax_fd* ax_fd_create(int fd, unsigned int when, ax_fd_cb_t cb, void* data)
{
    ax_fd* pstFd            = ALLOC(ax_fd);
    pstFd->fd               = fd;
    pstFd->when             = when;
    pstFd->cb               = cb;
    pstFd->data             = data;
    pstFd->last_active_time = ax_timestamp();
    return pstFd;
}

void ax_fd_destroy(ax_fd* fd)
{
    if(fd)
    {
        ax_fd_close(fd);
        FREE(fd);
    }
}

bool ax_fd_is_valid(ax_fd* fd)
{
    if(fd == NULL)
        return FALSE;
    return fd->fd > 0;
}


void ax_fd_close(ax_fd* fd)
{
    if(fd == NULL || fd->fd == -1)
        return;
    if(ax_fd_is_valid(fd))
        close(fd->fd);
    fd->fd   = -1;
    fd->when = 0;
}
